﻿using System;
using System.Collections.Generic;

namespace Accumulation.Common {
    /// <summary>
    /// 文件处理
    /// <remarks>
    /// MatchZhou - 2009/1/19
    /// </remarks>
    /// </summary>
    public class Files {
        /// <summary>
        /// 通过文件扩展名获取文件 ContentType，例：jpg 的 ContentType 为 "image/pjpeg"
        /// </summary>
        /// <param name="extension">扩展名，例：.jpg</param>
        /// <returns>ContentType，例：image/pjpeg)</returns>
        public static string GetContentTypeByExtentsion(string extension) {
            string contentType = string.Empty;
            extension = extension.ToLower();

            SortedList<string, string> fileContents = new SortedList<string, string>();
            fileContents.Add(".bmp", "image/bmp");
            fileContents.Add(".jpg", "image/pjpeg");
            fileContents.Add(".jpe", "image/pjpeg");
            fileContents.Add(".jpeg", "image/pjpeg");
            fileContents.Add(".pdf", "application/pdf");
            fileContents.Add(".png", "image/x-png");
            fileContents.Add(".gif", "image/gif");
            fileContents.Add(".rar", "application/octet-stream");
            fileContents.Add(".7z", "application/octet-stream");
            fileContents.Add(".zip", "application/x-zip-compressed");

            if (fileContents.ContainsKey(extension)) {
                int index = fileContents.IndexOfKey(extension);
                contentType = fileContents.Values[index];
            }

            return contentType;
        }
        /// <summary>
        /// 计算机存储单位转换方法
        /// </summary>
        /// <param name="fileSize">大小，字节</param>
        /// <returns>转换后的文字表示，例：2G，20.02M</returns>
        public static string GetFileSize(int fileSize) {
            string size = string.Empty;
            double threePow = Math.Pow(1024, 3);
            double twoPow = Math.Pow(1024, 2);

            if (fileSize >= threePow) {
                size = Math.Round(fileSize / threePow * 1000 / 1000, 2) + "G";
            }
            if (fileSize >= twoPow && fileSize < threePow) {
                size = Math.Round(fileSize / twoPow * 1000 / 1000, 2) + "M";
            }
            if (fileSize >= 1024 && fileSize < twoPow) {
                size = Math.Round((double)(fileSize / 1024 * 1000 / 1000), 2) + "K";
            }
            if (fileSize >= 0 && fileSize < 1024) {
                size = Math.Round((double)fileSize, 2) + "B";
            }
            return size;
        }
    }
}
